package org.nmgyjt.springboot.utils;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.apache.commons.lang.StringUtils;
import org.nmgyjt.springboot.beans.vo.Extattr;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static org.nmgyjt.springboot.utils.NMGYJTIDAASTokenUtils.log;
@Component
public class ZWWXUtils {
    @Value("${govwx.app-info.corpid}")
    private String corpid;
    @Value("${govwx.app-info.book-secret}")
    private String bookSecret;
    @Value("${govwx.gettoken-url}")
    private String gettokenUrl;
    @Value("${govwx.user-url}")
    private String userUrl;
    @Value("${govwx.user-update-url}")
    private String userUpdateUrl;
    @Value("${govwx.link.url}")
    private String linkUrl;
    @Value("${govwx.link.title}")
    private String linkTitle;
    @Value("${govwx.link.name}")
    private String linkName;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    public String getGovWxToken() {
        String ssoAccessToken=redisTemplate.opsForValue().get("ssoAccessToken");
        if(StringUtils.isEmpty(ssoAccessToken)){
            Map<String, Object> params = Maps.newHashMap();
            params.put("corpid", corpid);
            params.put("corpsecret", bookSecret);
            log.info("GovWX call http: {}", params);
            String responseBody = HttpUtil.get(gettokenUrl, params);
//        String responseBody = HttpUtil.get("http://111.56.38.122:90/cgi-bin/gettoken", params);
            log.info("政务微信[token]接口返回[{}]", responseBody);
            Map<String, Object> ssoAccessTokenMap = JSONUtil.toBean(responseBody, Map.class);
            if (ssoAccessTokenMap.isEmpty())
                return null;

            Integer errcode = (Integer) ssoAccessTokenMap.get("errcode");
            if (errcode != 0) {
                log.error("errcode:{}", errcode);
                return null;
            }

            ssoAccessToken = (String) ssoAccessTokenMap.get("access_token");
            log.info("GovWXssoAccessToken: {}", ssoAccessToken);
            if (StringUtils.isBlank(ssoAccessToken)) {
                log.warn("GovWXssoAccessToken is blank");
                return null;
            }
            redisTemplate.opsForValue().set("ssoAccessToken",ssoAccessToken,7000, TimeUnit.SECONDS);
        }

        return ssoAccessToken;
    }

    public Integer getZWUserInfo(String phone,String url, String ssoAccessToken) {
        Map<String, Object> params = Maps.newHashMap();
        params.put("access_token", ssoAccessToken);
        params.put("userid", phone);
        String responseBody = HttpUtil.get(userUrl, params);
        Map<String, Object> userMap = JSONUtil.toBean(responseBody, Map.class);
        Integer errcode = (Integer) userMap.get("errcode");
        if (errcode != 0) {
            log.info("<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<获取政微用户失败手机号:{}",phone);
            log.info("<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<获取政微用户失败信息:{}",userMap);
            return errcode;
        }
        Extattr extattrBean = new Extattr();
        Extattr.Attrs.Web web = new Extattr.Attrs.Web();
        web.setTitle(linkTitle);
        if(null==url){
            web.setUrl("");
        }else{
            web.setUrl(linkUrl+url);
        }
        List<Extattr.Attrs> attrs = Lists.newArrayList();
        Extattr.Attrs attr = new Extattr.Attrs();
        attr.setName(linkName);
        attr.setType(1);
        attr.setWeb(web);
        attrs.add(attr);
        extattrBean.setAttrs(attrs);
        userMap.put("extattr", extattrBean);

        String userUpdateBody = JSONUtil.toJsonStr(userMap);
        log.info("更新用户信息链接body{}", userUpdateBody);
        // 更新用户
        String updateUserResp = HttpUtil.post(userUpdateUrl + ssoAccessToken, userUpdateBody);
        log.info("更新用户信息链接result{}", updateUserResp);
        Map<String, Object> updateUserRespMap = JSONUtil.toBean(updateUserResp, Map.class);
        Integer updateUserRespErrcode = (Integer) updateUserRespMap.get("errcode");
        if (updateUserRespErrcode != 0) {
            log.error("更新用户信息失败：{}", updateUserResp);
            return updateUserRespErrcode;
        }
        return updateUserRespErrcode;
    }

    public String getUserInfo(String phone, String ssoAccessToken) {
        Map<String, Object> params = Maps.newHashMap();
        params.put("access_token", ssoAccessToken);
        params.put("userid", phone);
        String responseBody = HttpUtil.get(userUrl, params);
        return responseBody;
    }

}
